import React, { useState, useEffect } from 'react';
import './user.css';
import { Tooltip, Modal, Button, Checkbox, Input, Spin, Flex, Form, message } from 'antd';
import { CloseOutlined, RocketFilled, UserOutlined, LockOutlined } from '@ant-design/icons';
import { useForm } from 'antd/es/form/Form';

import { login as loginApi, register as registerApi } from '../../../api/user';
import { UserForm } from '../../../models/CommonModels';

const User = () => {
  const [form] = Form.useForm();
  // 用户表单状态
  const [userForm, setUserForm] = useState(new UserForm('', '', true));
  // 是否展示加载模式
  const [loading, setLoading] = useState(false);
  // 是否登录了
  const [logged, setLogged] = useState(false);
  // 是否要展示对话框
  const [showModal, setShowModal] = useState(false);
  // 是否为注册模式
  const [registerMode, setRegisterMode] = useState(false);

  // 检查是否已登录
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token) {
      setLogged(true);
    }
  }, []);

  // 处理点击
  const handleClick = () => {
    if (logged) {
      // 清除localStorage中的token和用户信息
      localStorage.removeItem('token');
      localStorage.removeItem('userId');
      localStorage.removeItem('username');
      localStorage.removeItem('userRole');
      
      // 触发用户登出事件
      const logoutEvent = new CustomEvent('user-logout');
      document.dispatchEvent(logoutEvent);
      
      setLogged(false);
      message.success('登出成功');
    } else {
      form.setFieldsValue(userForm);
      setShowModal(true);
    }
  };

  // 处理表单
  const handleForm = (values) => {
    setUserForm((prev) => ({ ...prev, ...values }));
    if (registerMode) {
      handleRegister(values);
    } else {
      handleLogin(values);
    }
  };

  // 表单值变化时实时更新状态
  const onValuesChange = (changedValues, allValues) => {
    setUserForm((prev) => ({ ...prev, ...allValues }));
  };

  // 处理登录
  const handleLogin = async (user) => {
    setLoading(true);
    try {
      // 返回值应包含完整axios响应，以便获取响应头
      const response = await loginApi({
        username: user.username,
        password: user.password,
        re: user.remember
      });

      console.log('登录响应:', response); // 添加调试日志
      console.log('登录响应类型:', typeof response);
      console.log('登录响应.data:', response.data);
      
      if (response.code === 200) {
        // 将token存储到localStorage
        localStorage.setItem('userId', response.data.id);
        localStorage.setItem('username', response.data.username);
        localStorage.setItem('userRole', response.data.role);
        
        const token = localStorage.getItem('token');
        console.log('登录成功，检查localStorage中的token:', token);
        
        if (!token && response.data && response.data.token) {
          console.log('从响应体中获取token:', response.data.token);
          localStorage.setItem('token', response.data.token);
        }
        
        const loginEvent = new CustomEvent('user-login', { 
          detail: { 
            userId: response.data.id,
            username: response.data.username
          } 
        });
        document.dispatchEvent(loginEvent);
        
        // config.js中有消息提示,这里的消息提示可以省略
        // message.success('登录成功');
        setLogged(true);
        handleCancel();
      } else {
        message.error(response.msg || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error); // 添加错误日志
      message.error(error.message || '登录失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理注册
  const handleRegister = async (user) => {
    setLoading(true);
    try {
      const response = await registerApi({
        username: user.username,
        password: user.password,
        re: user.remember
      });

      if (response.code === 200) {
        message.success('注册成功,即将跳转到登录页面');
        switchMode(1000);
      } else {
        message.error(response.msg || '注册失败');
      }
    } catch (error) {
      message.error(error.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理关闭对话框
  const handleCancel = () => {
    setLoading(false);
    setShowModal(false);
    setRegisterMode(false);
  };

  // 切换模式
  const switchMode = async (ms) => {
    setLoading(true);
    setTimeout(
      () => {
        setLoading(false);
        if (!registerMode) {
          form.setFieldsValue(new UserForm('', '', userForm.remember));
        }
        setRegisterMode(!registerMode);
      },
      typeof ms == 'number' ? ms : 200,
    );
  };

  return (
    <div className="user-info">
      <div className="login-container">
        <Tooltip title={logged ? '点击登出' : '点击登录'}>
          <div className="login-icon" onClick={handleClick}>
            <RocketFilled
              style={{
                fontSize: '30px',
                color: logged ? 'fuchsia' : 'aqua',
              }}
            />
          </div>
        </Tooltip>
        {/*对话框*/}
        <Modal
          open={showModal}
          onCancel={handleCancel}
          footer={null}
          width={'800px'}
          style={{
            top: '10px',
          }}
          wrapClassName={'wrap'}
          closable={false}
          maskClosable={false}
        >
          <div className="modal-container">
            <div className="left-container">
              <Spin spinning={loading}>
                <h1
                  style={{
                    position: 'relative',
                    top: '30px',
                    left: '30px',
                    height: '30px',
                    fontSize: '25px',
                    width: '150px',
                    color: 'black',
                    fontWeight: 'bold',
                  }}
                >
                  {registerMode ? '注册' : '欢迎回来!'}
                </h1>
                <Form
                  form={form}
                  name="login"
                  initialValues={userForm}
                  onValuesChange={onValuesChange}
                  style={{
                    position: 'relative',
                    top: '70px',
                    left: '10px',
                    maxWidth: 360,
                  }}
                  onFinish={handleForm}
                >
                  <Form.Item
                    name="username"
                    rules={[
                      {
                        required: true,
                        message: '用户名不为空',
                      },
                    ]}
                  >
                    <Input prefix={<UserOutlined />} placeholder="账号" />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[
                      {
                        required: true,
                        message: '密码不为空',
                      },
                    ]}
                  >
                    <Input.Password prefix={<LockOutlined />} type="password" placeholder="密码" />
                  </Form.Item>

                  {registerMode ? null : (
                    <Form.Item>
                      <Flex justify="space-between" align="center">
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                          <Checkbox>记住我</Checkbox>
                        </Form.Item>
                        <a href="">忘记密码</a>
                      </Flex>
                    </Form.Item>
                  )}

                  {registerMode ? (
                    <Form.Item
                      name="confirm"
                      label=""
                      dependencies={['password']}
                      hasFeedback
                      rules={[
                        {
                          required: true,
                          message: '密码不能为空',
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue('password') === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次输入的密码不匹配'));
                          },
                        }),
                      ]}
                    >
                      <Input.Password prefix={<LockOutlined />} placeholder="请再次输入密码" />
                    </Form.Item>
                  ) : null}

                  <Form.Item>
                    <Button block type="primary" htmlType="submit">
                      {registerMode ? '注册' : '登录'}
                    </Button>
                  </Form.Item>
                </Form>
                <a
                  style={{
                    position: 'relative',
                    top: '55px',
                    left: '115px',
                    width: '100px',
                    height: '30px',
                    fontSize: '15px',
                  }}
                  onClick={switchMode}
                >
                  {registerMode ? '注册成功?点击回到登录' : '还没有账号?点击立即注册'}
                </a>
              </Spin>
            </div>
            <div className="right-container">
              <img
                src="https://static.canva.cn/authenticating/auth_dialog/auth_dialog_zh-CN.jpg"
                style={{ position: 'absolute', width: '100', height: '100%' }}
                alt="background"
              />
            </div>
          </div>
          <div className="close-button" onClick={handleCancel}>
            <CloseOutlined
              style={{
                position: 'relative',
                top: '7px',
                left: '7px',
                fontSize: '16px',
                color: 'white',
              }}
            />
          </div>
        </Modal>
      </div>
    </div>
  );
};

export default User;
